import React, { Component, createRef } from 'react';
import { List, InputItem, Toast, Button } from 'antd-mobile';
import NavHeader from '@/components/NavHeader';
// import { doLoginApi } from '@/api/userApi'
import connect from './connect';

@connect
class Login extends Component {
  usernameRef = createRef()
  state = {
    username: '',
    hasUsernameError: false,
    password: '',
    hasPasswordError: false,
  }

  onErrorClick = (errorName, msg = '不合法') => {
    if (this.state[errorName]) {
      Toast.info(msg);
    }
  }

  onChange = (name, errorName, value) => {
    this.setState({
      [name]: value,
      [errorName]: /^\s*$/.test(value),
    });
  }

  dologin = async () => {
    let { hasUsernameError, hasPasswordError, username, password } = this.state
    if ([hasUsernameError, hasPasswordError].some(v => v)) {
      Toast.fail('账号和密码不能为空', 3, () => this.usernameRef.current.focus())
      return;
    }
    if ([username, password].some(v => v == '')) {
      Toast.fail('账号和密码不能为空@', 3, () => this.usernameRef.current.focus())
      return;
    }
    // 成功
    // let ret = await doLoginApi({ username, password })
    // console.log(ret);
    let code = await this.props.doLoginApiAction({ username, password })
    if (code === 0) {
      // Toast.info('账号登录成功', 2, () => this.props.history.replace('/center'))
      Toast.info('账号登录成功', 2, () => this.props.history.replace(this.props.jumpurl))
      return;
    }
    Toast.fail('账号或密码不正确', 3, () => this.usernameRef.current.focus())
  }

  render() {
    return (
      <div>
        <NavHeader left={true} onLeft={() => this.props.history.goBack()} leftText="返回">用户登录</NavHeader>
        <List>
          <List.Item multipleLine>
            <InputItem
              ref={this.usernameRef}
              type="text"
              placeholder="请输入账号信息"
              error={this.state.hasUsernameError}
              onErrorClick={() => this.onErrorClick('hasUsernameError', '账号不能为空')}
              onChange={value => this.onChange('username', 'hasUsernameError', value)}
              value={this.state.username}
            >账号:</InputItem>
          </List.Item>
          <List.Item multipleLine>
            <InputItem
              type="text"
              placeholder="请输入密码信息"
              error={this.state.hasPasswordError}
              onErrorClick={() => this.onErrorClick('hasPasswordError', '密码不能为空')}
              onChange={value => this.onChange('password', 'hasPasswordError', value)}
              value={this.state.password}
            >密码:</InputItem>
          </List.Item>
          <List.Item multipleLine>
            <Button type="primary" onClick={this.dologin}>登录账号</Button>
          </List.Item>
        </List>

      </div>
    );
  }
}

export default Login;
